<template>
  <div class="">
    <el-card class="box-card" shadow="never">
      <el-button
        size="small"
        style="margin-left: 15px"
        icon="el-icon-plus"
        class="iconadd"
        @click="handleAdd"
        >新增</el-button
      >
      <div class="content">
        <el-table
          :data="data"
          height="calc(55vh - 2px)"
          :header-cell-style="headerStyle"
          class="table"
        >
          <el-table-column align="center" label="序号" type="index" width="80">
          </el-table-column>
          <el-table-column
            align="center"
            prop="type"
            label="功能类型"
            show-overflow-tooltip
          >
            <template slot-scope="scope">
              <span v-if="scope.row.type == 'property'">属性</span>
              <span v-else-if="scope.row.type == 'service'">服务</span>
              <span v-else-if="scope.row.type == 'event'">事件</span>
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            prop="name"
            label="功能名称"
            show-overflow-tooltip
          >
          </el-table-column>
          <el-table-column
            align="center"
            prop="description"
            label="描述"
            show-overflow-tooltip
          >
          </el-table-column>
          <!-- <el-table-column align="center" prop="unit" label="组织机构" show-overflow-tooltip>
                    </el-table-column> -->
          <el-table-column
            align="center"
            prop="identifier"
            label="标识符"
            show-overflow-tooltip
          >
          </el-table-column>
          <el-table-column
            align="center"
            prop="dataTypeName"
            label="数据类型"
            show-overflow-tooltip
          >
          </el-table-column>
          <el-table-column
            align="center"
            prop="params"
            label="数据定义"
            show-overflow-tooltip
          >
          </el-table-column>
          <el-table-column
            align="center"
            prop="management"
            label="操作"
            width="150"
            show-overflow-tooltip
          >
            <template slot-scope="scope">
              <el-tooltip
                class="item"
                effect="dark"
                content="编辑"
                placement="bottom"
              >
                <i
                  @click="handleUpdate(scope.row)"
                  class="iconfont tianxie tableBtnIcon"
                ></i>
              </el-tooltip>
              <el-tooltip
                class="item"
                effect="dark"
                content="删除"
                placement="bottom"
              >
                <i
                  @click="onDel(scope.row)"
                  class="iconfont shanchu tableBtnIcon"
                ></i>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-card>
    <function-detail
      ref="functionDetailRef"
      :deviceType="deviceType"
      :model="model"
    />
  </div>
</template>

<script>
import FunctionDetail from "./modeuls/functionDetail.vue";
import tableStyleMixin from "@mixin/table-style";
import { reqThingModel } from "@/api/rule";

export default {
  props: {
    deviceType: {
      type: String,
      default: "",
    },
    model: {
      type: Object,
      default: () => ({}),
    },
  },
  components: {
    FunctionDetail,
  },
  mixins: [tableStyleMixin],
  data() {
    return {
      total: 0,
      page: {
        pageSize: 10,
        pageNum: 1,
      },
      query: {},
      loading: false,
      functionDetailRef: null,
      column: [
        {
          label: "功能类型",
          key: "type",
        },
        {
          label: "功能名称",
          key: "name",
        },
        {
          label: "描述",
          key: "description",
        },
        {
          label: "单位",
          key: "unit",
        },
        {
          label: "图标",
          key: "iconId",
          slot: true,
        },
        {
          label: "标识符",
          key: "identifier",
        },
        {
          label: "数据类型",
          key: "dataType",
          slot: true,
        },
        {
          label: "数据定义",
          key: "params",
          slot: true,
        },
      ],
      data: [],
    };
  },
  computed: {},
  watch: {
    model: {
      handler(newV) {
        if (newV) this.getInfo(newV);
      },
      deep: true,
      immediate: true,
    },
  },
  mounted() {
    // this.functionDetailRef = this.$refs.functionDetail
  },
  methods: {
    handleAdd() {
      this.$refs.functionDetailRef.openDialog();
    },
    handleUpdate(row) {
      let tmpModel = JSON.parse(JSON.stringify(row));
      console.log("tmpModel", tmpModel);
      if (!tmpModel.raw.dataType) {
        tmpModel.raw.dataType = {};
      }
      tmpModel.raw.inputData = tmpModel.raw.inputData || [];
      tmpModel.raw.outputData = tmpModel.raw.outputData || [];
      let prop = tmpModel.raw;
      const props = {};
      if (prop.dataType.type === "enum") {
        let enumSpecs = [];
        for (let p in prop.dataType.specs) {
          enumSpecs.push({
            name: prop.dataType.specs[p],
            value: p,
          });
        }
        props.enumItems = enumSpecs;
      } else if (prop.dataType.type === "bool") {
        props.boolItem = {
          _true: prop.dataType.specs["0"],
          _false: prop.dataType.specs["1"],
        };
      }
      console.log(row, props);
      this.$refs.functionDetailRef.openDialog(row, props);
    },
    async onDel(row) {
      const result = await this.$confirm("是否确认删除该数据?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).catch(() => {});
      if (result !== "confirm") return;
      // this.loading = true
      if (row.type === "property") {
        let index = this.model.properties.findIndex(
          (p) => p.identifier === row.identifier
        );
        this.model.properties.splice(index, 1);
      } else if (row.type === "service") {
        let index = this.model.services.findIndex(
          (s) => s.identifier === row.identifier
        );
        this.model.services.splice(index, 1);
      } else if (row.type === "event") {
        let index = this.model.events.findIndex(
          (e) => e.identifier === row.identifier
        );
        this.model.events.splice(index, 1);
      }
      this.submitThingModelChange();
    },
    async submitThingModelChange() {
      if (this.model) {
        this.model.services = this.model.services || [];
        this.model.properties = this.model.properties || [];
        this.model.events = this.model.events || [];
      }
      let res = await reqThingModel({
        productKey: this.deviceType,
        model: JSON.stringify(this.model),
      });
      if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
      this.$modal.notifySuccess("删除成功");
      //     this.loading = false
      this.$parent.getData();

      // saveObjectModel({
      //     productKey: this.deviceType,
      //     model: JSON.stringify(this.model)
      // }).then(() => {
      //     this.$parent.getData()
      // })
    },
    handleDel(row) {
      this.loading = true;
      if (row.type === "property") {
        let index = this.model.properties.findIndex(
          (p) => p.identifier === row.identifier
        );
        this.model.properties.splice(index, 1);
      } else if (row.type === "service") {
        let index = this.model.services.findIndex(
          (s) => s.identifier === row.identifier
        );
        this.model.services.splice(index, 1);
      } else if (row.type === "event") {
        let index = this.model.events.findIndex(
          (e) => e.identifier === row.identifier
        );
        this.model.events.splice(index, 1);
      }
      this.submitThingModelChange();
    },
    getInfo(model) {
      const modelObj = model || {
        properties: [],
        events: [],
        services: [],
      };
      let modelFuncs = [];
      modelObj.properties.forEach((p) => {
        let params = JSON.stringify(p.dataType.specs || "{}");
        modelFuncs.push({
          raw: p,
          type: "property",
          name: p.name,
          identifier: p.identifier,
          description: p.description,
          unit: p.unit,
          iconId: p.iconId,
          icon: p.icon,
          dataTypeName: p.dataType.type,
          params: params === "{}" ? "" : params,
        });
      });
      modelObj.events.forEach((e) => {
        let output = {};
        e.outputData.forEach((p) => {
          output[p.identifier] = p.name;
        });
        modelFuncs.push({
          raw: e,
          type: "event",
          name: e.name,
          description: e.description,
          identifier: e.identifier,
          dataTypeName: "-",
          params: JSON.stringify(output),
        });
      });
      modelObj.services.forEach((s) => {
        let input = {};
        s.inputData.forEach((p) => {
          input[p.identifier] = p.name;
        });
        let output = {};
        s.outputData.forEach((p) => {
          output[p.identifier] = p.name;
        });
        modelFuncs.push({
          raw: s,
          type: "service",
          name: s.name,
          description: s.description,
          identifier: s.identifier,
          dataTypeName: "-",
          params:
            "输入:" + JSON.stringify(input) + ",输出:" + JSON.stringify(output),
        });
      });
      console.log("modelFuncs", modelFuncs);
      this.data = modelFuncs;
    },
  },
};
</script>

<style lang="less" scoped>
@import url("~@views/style/tablePage.less");

::v-deep .el-card__body {
  padding: 0;
}

.box-card {
  min-height: 55vh;
  overflow-y: auto;
}

::v-deep .el-card__body {
  min-height: 55vh;
  overflow-y: auto;
}

.content {
  min-height: 55vh;
  overflow-y: auto;
}

.iconadd {
  background: #7367f0;
  color: #fff;
  border: none;
  margin: 15px 0 0 15px;
}
.tableBtnIcon {
  font-size: 18px;
  cursor: pointer;
  margin: 0 10px;
}
// 禁用鼠标移入时的背景色变化
::v-deep .el-table .el-table__body-wrapper tbody tr:hover > td {
  background-color: transparent !important; /* 使用 !important 确保覆盖 */
}
</style>
